package davidlauzon.activerecord.manager;

import java.sql.SQLException;
import java.util.List;

import davidlauzon.activerecord.nodes.CreateTableStatement;
import davidlauzon.activerecord.nodes.SqlStatement;
import davidlauzon.activerecord.nodes.Table;
import davidlauzon.activerecord.nodes.field.Field;


public class CreateTableStatementManager extends StatementManager
{
    private CreateTableStatement _statement;

    private Table    _table;
    private Field[]  _columns;
    private boolean  _ifNotExists;

    
    public CreateTableStatementManager() {
        super();
    }
    
    public void reset() {
        super.reset();
       _table       = null;
       _columns     = null;
       _ifNotExists = false;
    }
    
    public CreateTableStatementManager table(Table table) {
        _table = table;
        setConnection(    _table.getConnection() );
        setSqlSerializer( _table.getConnection().getSerializer() );
        return this;
    }
    
    public CreateTableStatementManager ifNotExists() {
        _ifNotExists = true;
        return this;
    }
    
    public CreateTableStatementManager columns(Field[] columns) {
        _columns = columns;
        return this;
    }
    
    public CreateTableStatementManager columns(List<Field> columns) {
        _columns = (Field[]) columns.toArray( new Field[columns.size()] );
        return this;
    }

    
    @Override
    protected SqlStatement buildStatement() {
        if (_columns == null)
            _columns = _table.getFieldsWithoutPK();
        
        _statement = new CreateTableStatement();
        _statement.setTable(_table);
        _statement.setColumns(_columns);
        _statement.setIfNotExists(_ifNotExists);
        
        return _statement;
    }
    
    public long execute() throws SQLException {
        String sql = this.toSql();
        return getConnection().executeUpdate( sql );
    }
}
